package com.developer.platform.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.developer.platform.domain.User;
import com.developer.platform.domain.repository.IUserRepository;
import com.developer.platform.infrastructure.data.mapper.UserMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Repository
public class UserRepository implements IUserRepository {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    public UserRepository(UserMapper userMapper,
                          PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public User findByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User findById(long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void save(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public void updateById(User user) {
        userMapper.updateById(user);
    }
}
